using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Decav.Gatsb.Application;
using Decav.Gatsb;
using Decav.Gatsb.Web;
using Decav.Gatsb.Data;

public partial class UserTileControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        tileDiv.Attributes["class"] = CssClass;

        if (!IsPostBack && User != null)
            InitializeTile();
    }

    private void InitializeTile()
    {
        userImage.ImageId = _user.Id;
        userName.Text = _user.Name.ToString();
        userNameLink.InnerText = userName.Text;
        userNameLink.HRef = viewProfileHref.HRef = string.Format("Person.aspx?id={0}", _user.Id);

        if (_user.RequestingUserCanSeeProfile)
        {
            viewProfileLi.Visible = true;
            userName.Visible = false;
            userNameLink.Visible = true;
        }
        else
        {
            viewProfileLi.Visible = false;
            userName.Visible = true;
            userNameLink.Visible = false;
        }

        UpdateFriendsLi();

        if (_user.RequestingUserCanSeeProfile)
        {
            LocationCheckin checkin = null;
            try
            {
                checkin = GatsbApplication.Current.GetUserLocation(_user);
            }
            catch (GatsbDataException)
            {
                currentLocationDiv.Visible = true;

                if (HttpContext.Current.User.Identity.IsAuthenticated)
                    currentLocationDiv.InnerText = string.Format("{0} does not want to share his current location.", User.Name.FirstName);
                else
                    currentLocationDiv.InnerText = "You must login to see this users location.";

                return;
            }

            if (checkin.LocationSpecified)
            {
                currentLocationDiv.Visible = true;
                currentLocationDiv.InnerHtml = string.Format("{0} is currently at <a href=\"Place.aspx?id={1}\">{2}</a> ({3}).",
                    _user.Name.FirstName, checkin.Location.Id, checkin.Location.Name, StringFormatting.ToTimeAgo(checkin.CheckinDate));
            }
            else
            {
                currentLocationDiv.Visible = false;
            }
        }
        else
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                currentLocationDiv.Visible = false;
            }
            else
            {
                currentLocationDiv.Visible = true;
                currentLocationDiv.InnerHtml = string.Format("You must <a href=\"Login.aspx?ReturnUrl={0}\">login</a> to see more about {1}.<br/>Not a member? <a href=\"CreateAccount.aspx?ReturnUrl={0}\">Create an account</a>",
                    Server.UrlEncode(Request.RawUrl), _user.Name.FirstName); ;
            }
        }
    }

    private Decav.Gatsb.User _user;

    /// <summary>
    /// Gets or sets the user the tile control displays.
    /// </summary>
    public Decav.Gatsb.User User
    {
        get
        {
            return _user;
        }
        set
        {
            _user = value;

            if (_user != null)
                UserId = _user.Id;
            else
                UserId = Guid.Empty;

            if (value != null)
                InitializeTile();
        }
    }

    /// <summary>
    /// Gets the ID of the user (Saved in viewstate);
    /// </summary>
    public Guid UserId
    {
        get
        {
            if (ViewState["UserId"] == null)
                return Guid.Empty;

            return (Guid)ViewState["UserId"];
        }
        private set
        {
            ViewState["UserId"] = value;
        }
    }

    /// <summary>
    /// Gets or sets the CSS class name used on the tile.
    /// </summary>
    public string CssClass
    {
        get
        {
            if (ViewState["CssClass"] == null)
                return "UserTile";
            else
                return (string)ViewState["CssClass"];
        }
        set
        {
            ViewState["CssClass"] = value;
            tileDiv.Attributes["class"] = value;
        }
    }

    protected void AddFriendButton_Click(object sender, EventArgs e)
    {
        GatsbApplication.Current.AddFriend(UserId);
        RefreshUser();
        UpdateFriendsLi();
    }

    protected void ConfirmFriendButton_Click(object sender, EventArgs e)
    {
        GatsbApplication.Current.AddFriend(UserId);
        RefreshUser();
        UpdateFriendsLi();
    }

    protected void RejectFriendButton_Click(object sender, EventArgs e)
    {
        GatsbApplication.Current.EndFriendship(UserId);
        RefreshUser();
        UpdateFriendsLi();
    }

    private void RefreshUser()
    {
        using (IGatsbDataAdapter adapt = GatsbApplication.Current.GetDataAdapter())
            _user = adapt.GetUser(UserId);
    }

    private void UpdateFriendsLi()
    {
        if (!HttpContext.Current.User.Identity.IsAuthenticated || _user.Id == GatsbApplication.Current.CurrentUser.Id)
        {
            addFriendLi.Visible = false;
            friendStatusLi.Visible = false;
            confirmFriendLi.Visible = false;

            return;
        }

        addFriendLi.Visible = (_user.Friendship == FriendshipStatus.NotFriends);
        friendStatusLi.Visible = (_user.Friendship == FriendshipStatus.FriendshipRequested || _user.Friendship == FriendshipStatus.MutualFriends);

        confirmPersonName.Text = _user.Name.FirstName.ToString();
        if (_user.Friendship == FriendshipStatus.FriendshipRequested)
            friendStatusLi.InnerText = "You have requested to add this person as your friend.";
        else
            friendStatusLi.InnerText = "You are friends with this person.";

        confirmFriendLi.Visible = (_user.Friendship == FriendshipStatus.UserRequestingFriendship);
    }
}
